#!/usr/bin/python3
# -*- coding:utf-8 -*-
""""
@Author: shijianbo
@Email:
@Time: 2022/7/26 16:32
@File: Aml__init__.py.py
"""
import inspect
import re

from BladeFerm.Lib.Common import logger
from DataTest.databases import getDb
from DataTest.databases.unisql import Unisql
from DataTest.env import Env
from CommonScripts.blade.polymerize import PolymerzeUtil
from faker import Faker

fk = Faker(locale='zh-CN')


# def blade_ui_test(*args,**kwargs):
#     '''
#     用于blade统一调用ui
#     '''
#     p = PolymerzeUtil()
#     # raise Exception(str(args)+str(kwargs))
#     _cls=args[0].pop('页面类')
#     _func=args[0].pop('方法')
#     _kwargs={}
#     for k,v in args[0].items():
#         if '(Object)' in k:
#             _kwargs[k[:-8]]=eval(v)
#             continue
#         elif '(Array)' in k:
#             _kwargs[k[:-7]] = eval(v)
#         else:
#             if isinstance(v,str):
#                 _kwargs[k]=v
#             elif isinstance(v,(float,int)):
#                 _kwargs[k]=v
#             elif isinstance(v,(dict,list,tuple,set)):
#                 _kwargs[k] = v
#             else:
#                 raise Exception(f'参数类型为{type(v)}')
#     with p[_cls]() as testUnit:
#         testUnit.run(_func,**_kwargs)

def blade_func_test(*args,**kwargs):
    '''
    用于blade统一调用common下方法
    '''
    p = PolymerzeUtil()
    _func = args[0].pop('方法')
    _expect = args[1]
    _kwargs = {}
    for k, v in args[0].items():
        if '(Object)' in k:
            _kwargs[k[:-8]] = eval(v)
        elif '(Array)' in k:
            _kwargs[k[:-7]] = eval(v)
        else:
            if isinstance(v, str):
                # todo:支持python脚本方式  <python:xxxx>  类似
                _kwargs[k] = v
            elif isinstance(v, (float,int)):
                _kwargs[k] = v
            elif isinstance(v, (dict, list, tuple, set)):
                _kwargs[k] = v
            else:
                raise Exception(f'参数类型为{type(v)}')
    _kwargs['env']=Env(**_kwargs).env
    _parameters=inspect.signature(p[_func]).parameters
    if 'expect' in _parameters or 'kwargs' in _parameters:
        _kwargs['expect']=_expect
    return p[_func](**_kwargs)


def blade_exec_sql(path, env=None, dml='delete,insert,merge,update'):
    '''
    blade执行sql脚本
    Args:
        path:sql脚本地址
        env:环境信息
        dml:执行sql的类型
    Returns:
        True or False
    '''
    # if dml.lower() == 'delete':
    #     redis_value = getRedis('hsrcm-rcmp:delete-status')
    #     if redis_value == '0':
    #         return True
    # path = getFilePath(fileName=path)
    sql = Unisql(path=path, dml=dml, env=Env(env).env)
    sql_list = []
    with getDb(env) as db:
        for _sql in sql:
            try:
                db.execsql(_sql)
                sql_list.append(_sql)
            except Exception as e:
                raise Exception(f'异常:{e},异常信息:{e.__str__()},sql:{_sql}')
        db.commit()
        sql_list_all = ";\n".join(sql_list)
        logger.debug(f"act current sql : \n{sql_list_all}")
        # 仅删除的时候处理
        if 'delete' in sql.dml:
            for _sql in sql:
                match = re.search(r"(?i)risk_id[ ]*=[ ]*'(\d+)'", _sql)
                if match:
                    risk_id = match.group(1)
                    # deleteRedis(keyWord=risk_id,env=Env(env).env)
                    break
        # 仅插入的时候处理
        if 'insert' in sql.dml:
            for _sql in sql:
                match = re.search(r"(?i)account_id[ ]*=[ ]*'(\d+)'", _sql)
                if match:
                    account_id = match.group(1)
                    # addAccountIdRedis(keyWord=account_id,env=Env(env).env)
                    break


def python_exec_sql(sql, env=None, **kwargs):
    '''
    blade执行sql脚本
    Args:
        path:sql脚本地址
        env:环境信息
        dml:执行sql的类型
    Returns:
        True or False
    '''
    # if dml.lower() == 'delete':
    #     redis_value = getRedis('hsrcm-rcmp:delete-status')
    #     if redis_value == '0':
    #         return True
    with getDb(env, **kwargs) as db:
        try:
            logger.debug(f"执行SQL：{sql}")
            result = db.execsql(sql)
            logger.debug(f"SQL结果：{result}")
            return result
        except Exception as e:
            raise Exception(f'异常:{e},异常信息:{e.__str__()},sql:{sql}')


if __name__ == '__main__':
    blade_exec_sql(r"E:/UI自动化/Project/金融反洗钱项目/web应用/客户信息管理/data/机构户信息查询.sql")
